<script setup lang="ts">
import { ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import RolePicker from '@/components/view/RolePicker.vue'
import FormUser from '@/components/form/FormUser.vue'
import { userDelete, userMyList, userSave } from '@/api/interface/web/user'

const fullscreenLoading = ref(false)

const roleRef = ref()

const searchForm = ref<any>({
  rangeDate: [],
})

const now = new Date()
const defaultTime: [Date, Date] = [
  new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0),
  new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59),
]

const roleId = ref<string>('')

const baseTableRef = ref()

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(searchForm.value).map((key) => {
    if (searchForm.value[key] || searchForm.value[key] === 0) {
      if (key === 'rangeDate') {
        if (searchForm.value[key]) {
          cond['createTime'] = searchForm.value[key][0]
          cond['updateTime'] = searchForm.value[key][1]
        }
      } else {
        cond[key] = searchForm.value[key]
      }
    }
  })

  cond['roleid'] = roleId.value
  return cond
}

const handleSearch = () => {
  baseTableRef.value.refresh()
}

const handleResetSearch = () => {
  searchForm.value = {
    rangeDate: [],
  }
  baseTableRef.value.refresh()
}

const changeRole = (data: any) => {
  roleId.value = data
  baseTableRef.value.refresh()
}

// 改变用户状态
const handleChangeStatus = (row: any, status: any) => {
  fullscreenLoading.value = true
  userSave({ id: row.id, status })
    .then(() => {
      ElMessage({
        message: '修改成功!',
        type: 'success',
      })
    })
    .finally(() => {
      fullscreenLoading.value = false
      baseTableRef.value.refreshStay()
    })
}

// 删除
const handleDelete = (row: any) => {
  const { id } = row
  ElMessageBox.confirm('确定删除用户?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false,
  }).then(() => {
    userDelete({ id })
      .then(() => {
        ElMessage({
          message: '删除成功!',
          type: 'success',
        })
      })
      .finally(() => {
        baseTableRef.value.refreshStay()
      })
  })
}

// 添加编辑
const dialogVisible = ref(false)

const addEditData = ref<any>({})

const addEditStatus = ref('add')

const formUserRef = ref()

const handleAdd = () => {
  addEditStatus.value = 'add'
  addEditData.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  addEditStatus.value = 'edit'
  addEditData.value = row
  dialogVisible.value = true
}

const handleDialogClose = () => {
  dialogVisible.value = false
}

const handleDialogSubmit = () => {
  formUserRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      const { id, nickname, username, password, roleid, status } = data
      userSave({ id, nickname, username, password, roleid, status })
        .then(() => {
          ElMessage({
            message: '操作成功!',
            type: 'success',
          })
          dialogVisible.value = false

          if (id) {
            baseTableRef.value.refreshStay()
          } else {
            baseTableRef.value.refresh()
          }
        })
        .finally(() => {
          fullscreenLoading.value = false
        })
    }
  })
}
</script>

<template>
  <BasePageWrapper v-loading.fullscreen="fullscreenLoading">
    <BasePage>
      <template #title>用户管理</template>
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <el-icon><Plus /></el-icon>
          </template>
          新增
        </el-button>
      </template>
      <template #searchbar>
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="关键字：">
            <el-input v-model="searchForm.nickname" placeholder="请输入关键字" />
          </el-form-item>
          <el-form-item label="创建时间：">
            <el-date-picker
              v-model="searchForm.rangeDate"
              type="datetimerange"
              range-separator="-"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="defaultTime"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="info" text bg @click="handleResetSearch">
              <template #icon>
                <el-icon><Refresh /></el-icon>
              </template>
              重置
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><Search /></el-icon>
              </template>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <div class="page-content-container">
        <div class="left">
          <RolePicker ref="roleRef" @change="changeRole"></RolePicker>
        </div>
        <div class="right">
          <BaseTable
            ref="baseTableRef"
            :init-table-method="userMyList"
            :condition-method="conditionMethod"
          >
            <el-table-column
              type="index"
              label="编号"
              align="center"
              header-align="center"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="nickname"
              label="昵称"
              min-width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="username"
              label="手机号/账号"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="roleName" label="角色" min-width="160">
              <template #default="scope">
                <el-tag
                  v-for="(item, index) in scope.row.roles"
                  :key="index"
                  type="success"
                  class="role-tag"
                  >{{ item.name }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="状态" width="160">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="1"
                  inactive-value="0"
                  @change="
                    (val: any) => {
                      handleChangeStatus(scope.row, val)
                    }
                  "
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              min-width="120"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </BaseTable>
        </div>
      </div>
    </BasePage>
  </BasePageWrapper>
  <BaseDialog v-model="dialogVisible">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogClose">取消</el-button>
      <el-button type="primary" @click="handleDialogSubmit">保存</el-button>
    </template>
    <FormUser ref="formUserRef" :data="addEditData" :status="addEditStatus"></FormUser>
  </BaseDialog>
</template>

<style lang="scss" scoped>
.page-content-container {
  @include rect(100%, 100%);
  @include flex(row, space-between, flex-start);
  .left {
    @include rect(220px, 100%);
    box-sizing: border-box;
    padding-bottom: 24px;
  }
  .right {
    @include rect(calc(100% - 240px), 100%);
    :deep(.role-tag) {
      margin-right: 10px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
    .icon-text-box {
      display: flex;
      justify-content: center;
      align-items: center;

      .icon-text {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 24px;
        cursor: pointer;
        .icon {
          margin-right: 5px;
          font-size: 16px;
        }
        .text {
          width: 2em;
        }
        .text.add {
          min-width: 4em;
        }
      }
      .icon-text:last-child {
        margin-right: 0;
      }
      .icon-text.info {
        color: var(--theme-color);
      }
      .icon-text.delete {
        color: #f56c6c;
      }
    }
  }
}
</style>
